var express = require('express');
var app = express();
var http = require('http').Server(app);
var bodyParser = require('body-parser');
var session = require('express-session');
var net = require('net');
var iconv = require('iconv-lite');
var car = require('./tcpClient_car_data.js');
const child_process = require('child_process');
var log_start = require('../lib/log_start.js');
var post = require('../lib/post.js');
var fs = require('fs');
// 输出日志信息
// log_start.control('trace',"aaaa");
//在线
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json());
app.all('*', function (req, res, next) {
    res.header("Access-Control-Allow-Origin", req.headers.origin);
    res.header("Access-Control-Allow-Credentials", true);
    res.header("Access-Control-Allow-Headers", "X-Requested-With,Content-Type");
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By", 'BIM');
    // res.header("Content-Type", "application/json;charset=utf-8");
    next();
});
app.use(express.static(__dirname + '/server_admin'));
// http服务
http.listen(2045, '0.0.0.0' ,function () {
        console.log('listening on *:2045');
});
var HOST = car.config.host;
var PORT = car.config.port;
var key = 'regist';
var clients = {};
// 终端发送命令
function command_buf(){
        // var arr = car.data.regist.split(" ");      
        var arr = car.data[key].split(" ");
        var len = arr.length;
        var buf = Buffer.allocUnsafe(len);
        for (var i = 0; i < arr.length; i++) {
            var str = arr[i];                       
            buf[i] = parseInt('0x'+str);           
        }
        var buf = create_jiaoyan(buf);
        // for (var client in clients) {
        //     clients[client].write(buf);
        // }       
        // var time = car.config.time;
        // setTimeout(command_buf,time);  
        return buf; 
}
// 校验码生成
function create_jiaoyan(buf){
    var result = buf[1];
    for (var j = 2; j < buf.length -2; j++) {
      //对每个字节进行异或运算
      result = result ^ buf[j];
    }
    buf[buf.length-2] = result;
    return buf;
}
function closesocket(){
    // client.end();
    console.log("please close me");
}
// *********************************************http服务**********************************************
var command_obj = {
    '1': 'regist',
    '2': 'jianquan',
    '3': 'media',
    '4': 'pos_report',//select_pos
    '5': 'driver_info'//driver
};
var p_send_obj = {
    select_pos:0x8201,
    driver:0x8700,
    photo:0x8801
};
var childs_obj = {

};
// 父进程向多个子进程发送消息
function process_send(data){
    // console.log(childs_obj);
    for (var i in childs_obj) {
        childs_obj[i].send(data);
    }
}
// 终端发送数据
app.post('/command/:statue',function(req,res){
    var statue = req.params.statue;
    var time = parseInt(req.body.time);
    if (statue == null || statue == '') {
        res.send({ret:-1,info:'no statue'})
    }
    if (time == null) {
       time = car.config.time;
    }
    // console.log(time);
    key = command_obj[statue];
    if (key != null && key != '') {
        var buf = command_buf();
        var data = {
            key:key, 
            time:time
        }
        process_send(data);
        res.send({ret:1, info:buf});
    }else{
        res.send({ret:-2, info:'no statue'});
    }
    
    
});
// 终端接收收据
var car_info = {

};
// 终端接收收据
app.post('/car_info',function(req,res){
      
})
// 平台发送数据
app.post('/p_send/:type', function(req,res){
   var type = req.params.type;
   var data = p_send_obj[type];
   if (data != null) {
       var url = car.config.httpurl;
       post.PostData2(data,url,function(ret,info){
         console.log(ret,info);
       })
   }
})
// 平台接收数据
app.get('/select_info', function(req,res){
   res.send({ret:1, info:car_info});
})

// 子进程启动多个终端
if (car.config.num > 0 && car.config.clild == 1) {
    var num = car.config.num;
    // 启动多个设备客户端
    var num_info = car.config.num_info;
    for (var i = 0; i < num; i++) {
        var filename = './tcpClient_car1.js';
        var child = child_process.fork(filename, {
                   silent: true
            }); 
        childs_obj[i] = child;
        // var time = num_info[i].time;
        child.stdout.on('data', (data) => {
          console.log(`输出：${data}`);
        });
        child.stderr.on('data', (data) => {
          console.log(`错误：${data}`);
        });
        child.on('exit', function(code, signal) {
        　　console.log('子进程已退出'+code);
        });
        child.on('close', (code,signal) => {
          console.log(`子进程退出码：${code}`);
        });
        child.on('error', (err) => {
          console.log('启动子进程失败。');
        });
    }
}
// 单进程循环启动
if (car.config.clild == 0) {
    for (var i = 0; i < car.config.num; i++) {
        var client = new net.Socket();
        clients[i] = client;
        client.connect(PORT, HOST, function () {
            console.log('CONNECTED TO: ' + HOST + ':' + PORT);
            command_buf();
        });
        client.on('data', function (data) {
            // console.log('data',data);
            //client.destroy();
        });
        // Add a 'close' event handler for the client socket
        client.on('close', function () {
            console.log('Connection closed');
        });
    }
}
function regist_buf2(){
    // 终端注册
    const buf = Buffer.allocUnsafe(59);
    // 标识位
    buf.writeUInt8(0x7e, 0);
    // 消息头
    // 消息id
    buf.writeUInt16BE(0x0100, 1);
    // 消息体属性
    buf.writeUInt16BE(0x2C, 3);
    // 终端手机号 6个字节
    buf.writeUInt16BE(0x0200, 5);
    buf.writeUInt16BE(0x0000, 7);
    buf.writeUInt16BE(0x0015, 9);
    // 消息流水号
    buf.writeUInt16BE(0x0025, 11);
    // 消息包封装项
    // 消息体
    // 省域id
    buf.writeUInt16BE(0x002C, 13);
    // 市县域id
    buf.writeUInt16BE(0x0133, 15);
    //制造商ID 5个字节
    buf.writeUInt16BE(0x3730, 17);
    buf.writeUInt16BE(0x3936, 19);
    buf.writeUInt8(0x30, 21);
    // 终端型号 20个字节
    // 54,37,2d,54,38,30,38,00,00,00,00,00,00,00,00,00,00,00,00,00
    buf.writeUInt16BE(0x5437, 22);
    buf.writeUInt16BE(0x2d54, 24);
    buf.writeUInt16BE(0x3830, 26);
    buf.writeUInt16BE(0x3830, 28);
    buf.writeUInt16BE(0x0000, 30);
    buf.writeUInt16BE(0x0000, 32);
    buf.writeUInt16BE(0x0000, 34);
    buf.writeUInt16BE(0x0000, 36);
    buf.writeUInt16BE(0x0000, 38);
    buf.writeUInt16BE(0x0000, 40);
    // 终端id 7个字节
    buf.writeUInt16BE(0x3033, 42);
    buf.writeUInt16BE(0x3239, 44);
    buf.writeUInt16BE(0x3137, 46);
    buf.writeUInt8(0x30, 48);
    // 车牌颜色
    buf.writeUInt8(0x01, 49);
    // 车辆标识
    var str = '粤B8888';
    var str2 = iconv.encode(str,'gbk');
    var len = str2.length;
    for (var i = 0; i < str2.length; i++) {
        buf[50 + i] = str2[i];
    }
    // var len = buf.write(str2,50);
    // console.log(str2,buf.slice(50, 50+len));
    // 计算校验码
    var result = buf[1];
    for (var i = 1; i < 50+len; i++) {
      //对每个字节进行异或运算
      result = result ^ buf[i + 1];
    }
    // 校验码
    buf.writeUInt8(result, 50+len);
    // 标识位
    buf.writeUInt8(0x7e, 51+len);    
    // 发送数据
    client.write(buf);
    // console.log(buf);
    setTimeout(regist_buf,5000);
}

